package crud.controller;

import crud.dao.pojo.UserInfo;
import crud.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/userInfo")
public class UserInfoController {
    @Autowired
    UserInfoService userInfoService;

    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> userlist() {
        //查询总数
        int totalCount = userInfoService.count();
        // 根据查询条件，分页获取客户列表
        List<UserInfo> userinfos = userInfoService.allUsers();
        // 创建对象result，保存查询结果数据
        Map<String, Object> result = new HashMap<String, Object>(2);
        result.put("total", totalCount);
        result.put("rows", userinfos);
        return result;
    }

    // 添加用户
    @PostMapping(value = "/addUser", produces = "text/html;charset=UTF-8",
            consumes = "application/x-www-form-urlencoded")
    @ResponseBody
    public String addUser( UserInfo ui) {
        try {
            userInfoService.addUserInfo(ui);
            return "{\"success\":\"true\",\"message\":\"用户添加成功\"}";
        } catch (Exception e) {
            return "{\"success\":\"false\",\"message\":\"用户添加失败\"}";
        }
    }
    // 修改用户
    @RequestMapping(value = "/updateUser", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String updateUser( UserInfo ui) {
        try {
            userInfoService.updateUserInfo(ui);
            return "{\"success\":\"true\",\"message\":\"用户修改成功\"}";
        } catch (Exception e) {
            return "{\"success\":\"false\",\"message\":\"用户修改失败\",\"errorMsg\":\"失败\"}";
        }
    }
    //删除用户
    @RequestMapping(value = "/deleteUser", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String deleteUser(UserInfo ui) {
        try {
            userInfoService.deleteUserInfo(ui);
            return "{\"success\":\"true\",\"message\":\"用户修改成功\"}";
        } catch (Exception e) {
            return "{\"success\":\"false\",\"message\":\"用户修改失败\"}";
        }
    }

}
